package com.lkl.demo.provider.controller;

import com.lkl.demo.common.constant.RabbitMQConstant;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/test")
public class TransactionController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 测试 RabbitMQ事务
     */
    @GetMapping
//    @Transactional(rollbackFor = Exception.class)
    public String test() {

        // 向 mq 发第一条消息
        HashMap<String, String> message1 = new HashMap<>();
        message1.put("phone", "110");
        message1.put("email", "110@163.com");
        rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_NAME, RabbitMQConstant.ROUTER_KEY_EXCHANGE, message1);

        // 模拟异常
//        int i = 1 / 0;

        // 向 mq 发第二条消息
        HashMap<String, String> message2 = new HashMap<>();
        message2.put("phone", "120");
        message2.put("email", "120@163.com");
        rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_NAME, RabbitMQConstant.ROUTER_KEY_EXCHANGE, message2);
        return "success";
    }

    @GetMapping("/confirm")
    public String test1() {
        rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_NAME, RabbitMQConstant.ROUTER_KEY_EXCHANGE, "likelong");
        return "success";
    }
}
